package com.mo.tools.encode;

/**
 * @author: e-Xingfu.Yang
 * @description:
 * @date:created in 2021/7/2 15:24
 * @modificed by:
 */
public class HexToStrUtil {

    public static final char[] chars = {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F'
    };
    public static final String str = "0123456789ABCDEF";

    /**
     * 字符串转换成为16进制
     *
     * @param str
     * @return
     */
    public static String strToHex(String str) {
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 16进制直接转换成为字符串
     *
     * @param hexStr
     * @return
     */
    public static String hexToStr(String hexStr) {
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

}
